package com.zhu.spider;

import cpm.haose.video.VideoDetail;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ExcelExport implements ExcelExportInterface{
    private HSSFWorkbook workbook;
    private HSSFSheet sheet;
    private int rowIndex;
    private String filePath;
    public ExcelExport() {

    }


    public ExcelExport(String filePath) {
        this.filePath = filePath;
        this.workbook = new HSSFWorkbook();//创建Excel文件(Workbook)
        this.sheet = workbook.createSheet("Test");//创建工作表(Sheet)
    }


    public List<VideoDetail> getVideoDetail(String filePath){
        try {
            File file =new File(filePath);
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(filePath)));
            HSSFSheet sheet = workbook.getSheet("Test");
            int maxRow = sheet.getLastRowNum();
            System.out.println("最大长度："+maxRow);
            List<VideoDetail> list = new ArrayList<>();
            for (int i = 1; i < maxRow; i++) {
                VideoDetail videoDetail = new VideoDetail();
                videoDetail.name = sheet.getRow(i).getCell(0).getStringCellValue();
                videoDetail.time = sheet.getRow(i).getCell(1).getStringCellValue();
                videoDetail.playCount = sheet.getRow(i).getCell(2).getStringCellValue();
                videoDetail.thumb = sheet.getRow(i).getCell(3).getStringCellValue();
                videoDetail.downLoadUrl = sheet.getRow(i).getCell(4).getStringCellValue();
                list.add(videoDetail);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public void setRowContent(String... content) {
        HSSFRow row = sheet.createRow(rowIndex);// 创建行,从0开始
        for (int i = 0; i < content.length; i++) {
            row.createCell(i).setCellValue(content[i]);// 创建行的单元格,也是从0开始
        }
        rowIndex++;
    }

    @Override
    public void exportContent() {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            workbook.write(out);//保存Excel文件
            out.close();//关闭文件流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
